package cn.jh.common.core.data.redis;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.scripting.ScriptSource;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.scripting.support.StaticScriptSource;
import org.springframework.util.Assert;

import java.io.IOException;

public class DefaultRedisScript<T> implements RedisScript<T>, InitializingBean {
    private ScriptSource scriptSource;
    private String sha1;
    private Class<T> resultType;
    private final Object shaModifiedMonitor = new Object();

    public DefaultRedisScript() {
    }

    public DefaultRedisScript(String script, Class<T> resultType) {
        this.setScriptText(script);
        this.resultType = resultType;
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.scriptSource, "Either script, script location, or script source is required");
    }

    public String getSha1() {
        Object var1 = this.shaModifiedMonitor;
        synchronized (this.shaModifiedMonitor) {
            if (this.sha1 == null || this.scriptSource.isModified()) {
                this.sha1 = DigestUtils.sha1DigestAsHex(this.getScriptAsString());
            }

            return this.sha1;
        }
    }

    public Class<T> getResultType() {
        return this.resultType;
    }

    public String getScriptAsString() {
        try {
            return this.scriptSource.getScriptAsString();
        } catch (IOException var2) {
            throw new ScriptingException("Error reading script text", var2);
        }
    }

    public void setResultType(Class<T> resultType) {
        this.resultType = resultType;
    }

    public void setScriptText(String scriptText) {
        this.scriptSource = new StaticScriptSource(scriptText);
    }

    public void setLocation(Resource scriptLocation) {
        this.scriptSource = new ResourceScriptSource(scriptLocation);
    }

    public void setScriptSource(ScriptSource scriptSource) {
        this.scriptSource = scriptSource;
    }
}